package com.azkj.album.view.fragment;

import static android.content.Context.CLIPBOARD_SERVICE;
import static androidx.core.content.ContextCompat.getSystemService;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.azkj.album.R;
import com.azkj.album.dto.LoginBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.Constants;
import com.azkj.album.network.utils.StoreUtils;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.presenter.UserPresenter;
import com.azkj.album.view.activity.LoginActivity;
import com.azkj.album.view.activity.MainCollectActivity;
import com.azkj.album.view.activity.MemberActivity;
import com.azkj.album.view.activity.RegisterActivity;
import com.azkj.album.view.activity.WebViewActivity;
import com.azkj.album.view.base.BaseFragment;
import com.azkj.album.view.iview.IUserView;
import com.azkj.album.view.widgets.dialog.CommonDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.InputConfirmPopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class UserFragment extends BaseFragment implements IUserView {

    @BindView(R.id.tv_name)
    TextView mTvName;

    @BindView(R.id.tv_wx_label)
    TextView mTvWxLabel;

    @BindView(R.id.tv_vip)
    TextView mTvVip;

    @BindView(R.id.tv_vip_time)
    TextView mTvVipTime;

    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.iv_vip_logo)
    ImageView mIvVip;

    @BindView(R.id.rl_user_bg)
    RelativeLayout mRlUserBg;
    @BindView(R.id.ll_vip_info)
    LinearLayout mLlVip;
    @BindView(R.id.iv_amend)
    ImageView mIvAmend;

    @BindView(R.id.tv_versions)
    TextView tvVersions;

    private boolean isVip;


    private UserPresenter mPresenter;


    private InputConfirmPopupView amendNameDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_user;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        initListener();
    }

    private void initListener() {
    }

    @Override
    public void onVisible() {
        super.onVisible();
        initUserInfo();
    }

    private void initData() {
        mPresenter = new UserPresenter(this);
        initUserInfo();
        getVersion();

    }

    private void getVersion(){
        PackageManager packageManager = getContext().getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
            String versionName = packageInfo.versionName;
            tvVersions.setText("版本：v" + versionName);
        }catch (PackageManager.NameNotFoundException e){
            e.printStackTrace();
        }
    }

    private void initUserInfo() {
        LoginBean loginBean = ConfigStorage.getInstance().getUserBean();
        if (loginBean != null && loginBean.getUserinfo() != null) {
            isVip = loginBean.getUserinfo().getIs_vip() == 1;
            mTvName.setText(loginBean.getUserinfo().getNickname());
            mTvPhone.setText(loginBean.getUserinfo().getMobile());
//            mTvWxLabel.setVisibility((boolean) StoreUtils.get("isWX", false) ? View.VISIBLE : View.GONE);
            mTvName.setTextColor(getResources().getColor(isVip ? R.color.white : R.color.black));
            mRlUserBg.setBackgroundResource(isVip ? R.mipmap.bg_user_vip : R.mipmap.bg_user);
            tvVersions.setTextColor(isVip ? Color.WHITE : Color.BLACK);
            mIvVip.setVisibility(isVip ? View.VISIBLE : View.GONE);
            mLlVip.setVisibility(isVip ? View.VISIBLE : View.GONE);
            mTvVip.setText(isVip ? "我的VIP" : "成为VIP");
            mTvVipTime.setText(loginBean.getUserinfo().getVip_time());

        }
    }

    @OnClick({R.id.iv_usually_0, R.id.iv_usually_1, R.id.iv_usually_2, R.id.iv_usually_3,
            R.id.iv_tool_0, R.id.iv_tool_1, R.id.iv_tool_2, R.id.iv_tool_3,
            R.id.iv_tool_4, R.id.iv_tool_5, R.id.iv_tool_6, R.id.iv_tool_7, R.id.iv_amend})
    void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.iv_usually_0://vip
                intent = new Intent(getActivity(), MemberActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_usually_1://客服
                new CommonDialog.Builder(getContext()).setTitle("联系客服")
                        .setDesc("客服信息：baopan2333")
                        .setButton("", "复制微信号")
                        .setOnClickListener((dialog, confirm) -> {
                            ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(CLIPBOARD_SERVICE);
                            if (clipboard != null) {
                                ClipData clip = ClipData.newPlainText("text", "baopan2333");
                                clipboard.setPrimaryClip(clip);
                                Toast.makeText(getActivity(), "已复制到剪贴板", Toast.LENGTH_SHORT).show();
                            }
                            dialog.dismiss();
                        }).show();
                break;
            case R.id.iv_usually_2://收藏
                intent = new Intent(getActivity(), MainCollectActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_usually_3://社区图片
                ToastUtils.showCenterToast("敬请期待");

                break;
            case R.id.iv_tool_0://版本检测
                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_USER_UPDATE_CLICKED));
                break;
            case R.id.iv_tool_1://修改密码
                RegisterActivity.startActivity(getActivity(), 4, null);
                break;
            case R.id.iv_tool_2://修改手机号
                RegisterActivity.startActivity(getActivity(), 6, null);
                break;
            case R.id.iv_tool_3://协议
                intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", Constants.WEB_PAGE_PROTOCOL_2);
                startActivity(intent);
                break;
            case R.id.iv_tool_4://隐私
                intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "隐私政策");
                intent.putExtra("url", Constants.WEB_PAGE_PROTOCOL_1);
                startActivity(intent);
                break;
            case R.id.iv_tool_5://分享
                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_USER_SHARE_CLICKED));
                break;
            case R.id.iv_tool_6://注销
                new CommonDialog.Builder(getContext()).setTitle("提示")
                        .setDesc("您是否要注销该账号，如果注销则所有数据将会被删除！")
                        .setButton("取消", "确定")
                        .setOnClickListener((dialog, confirm) -> {
                            if (confirm) {
                                new CommonDialog.Builder(getContext()).setTitle("提示")
                                        .setDesc("请您再次确定，是否注销该账号?")
                                        .setButton("取消", "确定")
                                        .setOnClickListener((dialog2, confirm2) -> {
                                            if (confirm2) {
                                                mPresenter.clearUser();
                                            }
                                            dialog2.dismiss();
                                        }).show();
                            }
                            dialog.dismiss();
                        }).show();
                break;
            case R.id.iv_tool_7://退出

                new CommonDialog.Builder(getContext()).setTitle("提示")
                        .setDesc("确定退出登录吗?")
                        .setButton("取消", "确定")
                        .setOnClickListener((dialog2, confirm2) -> {
                            if (confirm2) {
                                mPresenter.logout();
                                ToastUtils.showCenterToast("退出成功");
                                startActivity(new Intent(getContext(), LoginActivity.class));
                            }
                            dialog2.dismiss();
                        }).show();


                break;
            case R.id.iv_amend:
                XPopup.setPrimaryColor(Color.WHITE);
                amendNameDialog = new XPopup.Builder(getContext())
                        .autoDismiss(false)
                        .asInputConfirm("修改昵称", "", mTvName.getText().toString(), "", new OnInputConfirmListener() {
                            @Override
                            public void onConfirm(String text) {
                                mPresenter.hasNickName(text);
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {

                            }
                        }, R.layout.dialog_amend_name);
                if (amendNameDialog != null && !amendNameDialog.isShow()){
                    amendNameDialog.show();
                }

                break;
        }
    }

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_USER_PHONE_CHANGED:
                initUserInfo();
                break;
        }
    }

    @Override
    public void clearUserSuccess() {
        ToastUtils.showCenterToast("注销成功");
        StoreUtils.clear();
        startActivity(new Intent(getContext(), LoginActivity.class));
    }

    @Override
    public void clearUserFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void hasNickName(boolean isHasNickName, String name, Map<String, Object> body, TextView textView) {
        if (isHasNickName){
            mPresenter.changenickName(name);
        }else {
            ToastUtils.showCenterToast("该昵称已被占用，请更换昵称");
        }
    }

    @Override
    public void changeNameSuccess(boolean isChangeSuccess, String name) {
        if (amendNameDialog != null && amendNameDialog.isShow()){
            amendNameDialog.dismiss();
        }
        if (isChangeSuccess){
            ToastUtils.showCenterToast("更改成功");
            mTvName.setText(name);
        }
    }
}
